home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / rdflib / util.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  8.2 KB  |  237 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from rdflib.URIRef import URIRef
  5. from rdflib.BNode import BNode
  6. from rdflib.Literal import Literal
  7. from rdflib.Variable import Variable
  8. from rdflib.Graph import Graph, QuotedGraph
  9. from rdflib.Statement import Statement
  10. from rdflib.exceptions import SubjectTypeError, PredicateTypeError, ObjectTypeError, ContextTypeError
  11. from rdflib.compat import rsplit
  12. from cPickle import loads
  13.  
  14. def list2set(seq):
  15.     seen = set()
  16.     return _[1]
  17.  
  18.  
  19. def first(seq):
  20.     for result in seq:
  21.         return result
  22.     
  23.  
  24.  
  25. def uniq(sequence, strip = 0):
  26.     '''removes duplicate strings from the sequence.'''
  27.     set = { }
  28.     if strip:
  29.         (map,)((lambda val, default: set.__setitem__(val.strip(), default)), sequence, [])
  30.     else:
  31.         map(set.__setitem__, sequence, [])
  32.     return set.keys()
  33.  
  34.  
  35. def more_than(sequence, number):
  36.     '''Returns 1 if sequence has more items than number and 0 if not.'''
  37.     i = 0
  38.     for item in sequence:
  39.         i += 1
  40.         if i > number:
  41.             return 1
  42.     
  43.     return 0
  44.  
  45.  
  46. def term(str, default = None):
  47.     '''See also from_n3'''
  48.     if not str:
  49.         return default
  50.     if str.startswith('<') and str.endswith('>'):
  51.         return URIRef(str[1:-1])
  52.     if str.startswith('"') and str.endswith('"'):
  53.         return Literal(str[1:-1])
  54.     if str.startswith('_'):
  55.         return BNode(str)
  56.     msg = "Unknown Term Syntax: '%s'" % str
  57.     raise Exception(msg)
  58.  
  59. from time import mktime, time, gmtime, localtime, timezone, altzone, daylight
  60.  
  61. def date_time(t = None, local_time_zone = False):
  62.     """http://www.w3.org/TR/NOTE-datetime ex: 1997-07-16T19:20:30Z
  63.  
  64.     >>> date_time(1126482850)
  65.     '2005-09-11T23:54:10Z'
  66.  
  67.     >>> date_time(1126482850, local_time_zone=True)
  68.     '2005-09-11T19:54:10-04:00'
  69.  
  70.     >>> date_time(1)
  71.     '1970-01-01T00:00:01Z'
  72.  
  73.     >>> date_time(0)
  74.     '1970-01-01T00:00:00Z'
  75.     """
  76.     if t is None:
  77.         t = time()
  78.     
  79.     if local_time_zone:
  80.         time_tuple = localtime(t)
  81.         if time_tuple[8]:
  82.             tz_mins = altzone // 60
  83.         else:
  84.             tz_mins = timezone // 60
  85.         tzd = '-%02d:%02d' % (tz_mins // 60, tz_mins % 60)
  86.     else:
  87.         time_tuple = gmtime(t)
  88.         tzd = 'Z'
  89.     (year, month, day, hh, mm, ss, wd, y, z) = time_tuple
  90.     s = '%0004d-%02d-%02dT%02d:%02d:%02d%s' % (year, month, day, hh, mm, ss, tzd)
  91.     return s
  92.  
  93.  
  94. def parse_date_time(val):
  95.     '''always returns seconds in UTC
  96.  
  97.     # tests are written like this to make any errors easier to understand
  98.     >>> parse_date_time(\'2005-09-11T23:54:10Z\') - 1126482850.0
  99.     0.0
  100.  
  101.     >>> parse_date_time(\'2005-09-11T16:54:10-07:00\') - 1126482850.0
  102.     0.0
  103.  
  104.     >>> parse_date_time(\'1970-01-01T00:00:01Z\') - 1.0
  105.     0.0
  106.  
  107.     >>> parse_date_time(\'1970-01-01T00:00:00Z\') - 0.0
  108.     0.0
  109.     >>> parse_date_time("2005-09-05T10:42:00") - 1125916920.0
  110.     0.0
  111.     '''
  112.     if 'T' not in val:
  113.         val += 'T00:00:00Z'
  114.     
  115.     (ymd, time) = val.split('T')
  116.     hms = time[0:8]
  117.     tz_str = time[8:]
  118.     if not tz_str or tz_str == 'Z':
  119.         time = time[:-1]
  120.         tz_offset = 0
  121.     else:
  122.         signed_hrs = int(tz_str[:3])
  123.         mins = int(tz_str[4:6])
  124.         secs = (cmp(signed_hrs, 0) * mins + signed_hrs * 60) * 60
  125.         tz_offset = -secs
  126.     (year, month, day) = ymd.split('-')
  127.     (hour, minute, second) = hms.split(':')
  128.     t = mktime((int(year), int(month), int(day), int(hour), int(minute), int(second), 0, 0, 0))
  129.     t = (t - timezone) + tz_offset
  130.     return t
  131.  
  132.  
  133. def from_n3(s, default = None, backend = None):
  134.     ''' Creates the Identifier corresponding to the given n3 string. WARNING: untested, may contain bugs. TODO: add test cases.'''
  135.     if not s:
  136.         return default
  137.     if s.startswith('<'):
  138.         return URIRef(s[1:-1])
  139.     if s.startswith('"'):
  140.         (value, rest) = rsplit(s, '"', 1)
  141.         value = value[1:]
  142.         if rest.startswith('^^'):
  143.             datatype = rest[3:-1]
  144.         else:
  145.             datatype = None
  146.         value = value.replace('\\"', '"').replace('\\\\', '\\').decode('unicode-escape')
  147.         return Literal(value, language, datatype)
  148.     if s.startswith('{'):
  149.         identifier = from_n3(s[1:-1])
  150.         return QuotedGraph(backend, identifier)
  151.     if s.startswith('['):
  152.         identifier = from_n3(s[1:-1])
  153.         return Graph(backend, identifier)
  154.     if s.startswith('_:'):
  155.         return BNode(s[2:])
  156.     return BNode(s)
  157.  
  158.  
  159. def check_context(c):
  160.     if not isinstance(c, URIRef) or isinstance(c, BNode):
  161.         raise ContextTypeError('%s:%s' % (c, type(c)))
  162.     isinstance(c, BNode)
  163.  
  164.  
  165. def check_subject(s):
  166.     ''' Test that s is a valid subject identifier.'''
  167.     if not isinstance(s, URIRef) or isinstance(s, BNode):
  168.         raise SubjectTypeError(s)
  169.     isinstance(s, BNode)
  170.  
  171.  
  172. def check_predicate(p):
  173.     ''' Test that p is a valid predicate identifier.'''
  174.     if not isinstance(p, URIRef):
  175.         raise PredicateTypeError(p)
  176.     isinstance(p, URIRef)
  177.  
  178.  
  179. def check_object(o):
  180.     ''' Test that o is a valid object identifier.'''
  181.     if not isinstance(o, URIRef) and isinstance(o, Literal) or isinstance(o, BNode):
  182.         raise ObjectTypeError(o)
  183.     isinstance(o, BNode)
  184.  
  185.  
  186. def check_statement(.0):
  187.     (s, p, o) = .0
  188.     if not isinstance(s, URIRef) or isinstance(s, BNode):
  189.         raise SubjectTypeError(s)
  190.     isinstance(s, BNode)
  191.     if not isinstance(p, URIRef):
  192.         raise PredicateTypeError(p)
  193.     isinstance(p, URIRef)
  194.     if not isinstance(o, URIRef) and isinstance(o, Literal) or isinstance(o, BNode):
  195.         raise ObjectTypeError(o)
  196.     isinstance(o, BNode)
  197.  
  198.  
  199. def check_pattern(.0):
  200.     (s, p, o) = .0
  201.     if s:
  202.         if not isinstance(s, URIRef):
  203.             pass
  204.         if not isinstance(s, BNode):
  205.             raise SubjectTypeError(s)
  206.     not isinstance(s, BNode)
  207.     if p and not isinstance(p, URIRef):
  208.         raise PredicateTypeError(p)
  209.     not isinstance(p, URIRef)
  210.     if o:
  211.         if not isinstance(o, URIRef) and isinstance(o, Literal):
  212.             pass
  213.         if not isinstance(o, BNode):
  214.             raise ObjectTypeError(o)
  215.     not isinstance(o, BNode)
  216.  
  217.  
  218. def graph_to_dot(graph, dot):
  219.     ''' Turns graph into dot (graphviz graph drawing format) using pydot. '''
  220.     import pydot
  221.     nodes = { }
  222.     for s, o in graph.subject_objects():
  223.         for i in (s, o):
  224.             if i not in nodes.keys():
  225.                 nodes[i] = i
  226.                 continue
  227.         
  228.     
  229.     for s, p, o in graph.triples((None, None, None)):
  230.         dot.add_edge(pydot.Edge(nodes[s], nodes[o], label = p))
  231.     
  232.  
  233. if __name__ == '__main__':
  234.     import doctest
  235.     doctest.testmod()
  236.  
  237.